/*****************************************************************************************
   
   Copyright (c) Microsoft Corporation. All rights reserved.

   Use of this code sample is subject to the terms of the Microsoft
   Permissive License, a copy of which should always be distributed with
   this file.  You can also access a copy of this license agreement at:
   http://www.microsoft.com/resources/sharedsource/licensingbasics/permissivelicense.mspx

 ****************************************************************************************/

using System;

namespace GrooveCommands
{
	class GrooveReplaceFormsRecordField : CommandUtils.GrooveUtilBase
	{
		private string m_SpaceURI;
		private string m_FormsToolURI;
		private string m_FieldName;
		private string m_WhereClause;
		private string m_OldValue;
		private string m_NewValue;

		private bool m_UnreadOnly;

		[STAThread]
		static void Main(string[] i_Arguments)
		{
			CommandUtils.UtilAppMain.RunApplication(new GrooveReplaceFormsRecordField(i_Arguments));
		}
	
		public GrooveReplaceFormsRecordField(string[] i_Arguments)
			: base (i_Arguments)
		{
			base.UsageMessage = "GrooveReplaceFormsRecordField [PARAMS...]";
			base.HelpMessage = 
				"GrooveReplaceFormsRecordField\r\n\t" + 
				"Replaces field value for queried records for specified forms tool\r\n" +
				"Parameters:\r\n\t" +
				"/FormsTool=          The Web Services URI for the Groove forms tool\r\n\t" +
				"/FieldName=          Name of field whose value will be changed\r\n\t" +
				"/OldValue=           Old value of field\r\n\t" +
				"/NewValue=           New value of field\r\n\t" +
				"[/WhereClause=       Query parameters (see Groove doc for syntax)]\r\n\t" +
				"[/UnreadOnly         Indicates to return unread records only]\r\n\t" +
				"[/Account=           The Web Services URI for the Groove account]\r\n\t" +
				"[/Identity=          The Web Services URI for the Groove identity]\r\n\t" +
				"[/WhereClause=       Query parameters (see Groove doc for syntax)]\r\n\t" +
				"[/RequestKey=        Token used to communicate Groove host]\r\n\t" +
				"[/Host=              The remote Groove host name to issue commands to]\r\n\t" +
				"[/Port=              The remote Groove host port to issue commands to]\r\n\t" +
				"[/Timeout=           Timeout (in ms) for Web Services method execution]\r\n\t" +
				"[/X=                 Configuration file to use for parameter input]\r\n\t" +
				"\r\n";
		}

		public override CheckResult CheckParameters()
		{
			CommandUtils.UtilBase.CheckResult CheckResult = base.CheckParameters();
			if (CheckResult != CommandUtils.UtilBase.CheckResult.Succeeded )
				return CheckResult;
		
			m_FormsToolURI = base.GetParameterValue("FormsTool");
			if (System.String.IsNullOrEmpty(m_FormsToolURI))
			{
				base.DisplayUsage("You must specify a forms tool.");
				return CommandUtils.UtilBase.CheckResult.Failed;
			}

			//  The format for a Tool URI is:
			//    "/GWS/Groove/2.0/Tools/grooveTelespace/fuzvzuaax9wjv72dwfa2sxyd4vabu8bae74s9k2/ToolContainer/vk2xck8tanv5i"
			//
			//  The format for a Space URI is:
			//    "/GWS/Groove/2.0/Spaces/grooveTelespace/fuzvzuaax9wjv72dwfa2sxyd4vabu8bae74s9k2"

			string[] FormsToolURIParts = m_FormsToolURI.Split(new char[]{'/'});
			m_SpaceURI = "/GWS/Groove/2.0/Spaces/grooveTelespace/" + FormsToolURIParts[6];

			m_WhereClause = base.GetParameterValue("WhereClause");
			if (System.String.IsNullOrEmpty(m_WhereClause))
				m_WhereClause = "";
		
			m_FieldName = base.GetParameterValue("FieldName");
			if (System.String.IsNullOrEmpty(m_FieldName))
			{
				base.DisplayUsage("You must specify a field name.");
				return CommandUtils.UtilBase.CheckResult.Failed;
			}

			m_OldValue = base.GetParameterValue("OldValue");
			if (System.String.IsNullOrEmpty(m_OldValue))
			{
				base.DisplayUsage("You must specify am old value.");
				return CommandUtils.UtilBase.CheckResult.Failed;
			}

			m_NewValue = base.GetParameterValue("NewValue");
			if (System.String.IsNullOrEmpty(m_NewValue))
			{
				base.DisplayUsage("You must specify am new value.");
				return CommandUtils.UtilBase.CheckResult.Failed;
			}

			m_UnreadOnly = base.GetParameterValueFlag("UnreadOnly");

			return base.CheckUnusedParameters();
		}

		public override CommandUtils.UtilBase.CheckResult Run()
		{
			GrooveWebServicesV12Helpers.Space Space = null;

			try
			{
				Space = base.Identity.OpenSpace(m_SpaceURI);
			}
			catch (System.Exception Exception)
			{
				base.StandardError.WriteLine("Unable to open space: " + Exception.Message);
				throw Exception;
			}

			GrooveWebServicesV12Helpers.Tool Tool = null;
			
			try
			{
				Tool = Space.OpenTool(m_FormsToolURI);
			}
			catch (System.Exception Exception)
			{
				base.StandardError.WriteLine("Unable to open forms tool: " + Exception.Message);
				throw Exception;
			}

            System.Data.DataSet DataSet = null;

            if (Tool is GrooveWebServicesV12Helpers.Forms.FormsTool)
            {
                GrooveWebServicesV12Helpers.Forms.FormsTool FormsTool = (GrooveWebServicesV12Helpers.Forms.FormsTool)Tool;
                GrooveWebServicesV12Helpers.Forms.RecordDataSet RecordDataSet = null;

                try
                {
                    RecordDataSet = FormsTool.QueryRecords
                        (
                        m_WhereClause,
                        false,			//  i_IncludeAttachments
                        m_UnreadOnly
                        );
                }
                catch (System.Exception Exception)
                {
                    base.StandardError.WriteLine("Unable to query records: " + Exception.Message);
                    throw Exception;
                }

                DataSet = RecordDataSet.ToDataSet();
            }
            else
            {
                GrooveWebServicesV12Helpers.Forms2.FormsTool FormsTool = (GrooveWebServicesV12Helpers.Forms2.FormsTool)Tool;
                GrooveWebServicesV12Helpers.Forms2.RecordDataSet RecordDataSet = null;

                try
                {
                    RecordDataSet = FormsTool.QueryRecords
                        (
                        m_WhereClause,
                        false,			//  i_IncludeAttachments
                        m_UnreadOnly
                        );
                }
                catch (System.Exception Exception)
                {
                    base.StandardError.WriteLine("Unable to query records2: " + Exception.Message);
                    throw Exception;
                }

                DataSet = RecordDataSet.ToDataSet();
            }

			System.Data.DataRow[] DataRows = null;

            foreach (System.Data.DataTable DataTable in DataSet.Tables)
            {
                if (DataTable.ParentRelations.Count != 0)
                    continue;

                try
                {
                    DataRows = DataTable.Select(m_FieldName + " = '" + m_OldValue + "'");
                }
                catch (System.Exception Exception)
                {
                    base.StandardError.WriteLine("Unable to query dataset: " + Exception.Message);
                    throw Exception;
                }

                if (DataRows.Length > 0)
                {
                    foreach (System.Data.DataRow DataRow in DataRows)
                        DataRow[m_FieldName] = m_NewValue;

                    DataSet.AcceptChanges();
                }
            }

            if (Tool is GrooveWebServicesV12Helpers.Forms.FormsTool)
            {
                GrooveWebServicesV12Helpers.Forms.FormsTool FormsTool = (GrooveWebServicesV12Helpers.Forms.FormsTool)Tool;

                try
                {
                    FormsTool.UpdateRecords(new GrooveWebServicesV12Helpers.Forms.RecordDataSet(DataSet));
                }
                catch (System.Exception Exception)
                {
                    base.StandardError.WriteLine("Unable to update dataset: " + Exception.Message);
                    throw Exception;
                }
            }
            else
            {
                GrooveWebServicesV12Helpers.Forms2.FormsTool FormsTool = (GrooveWebServicesV12Helpers.Forms2.FormsTool)Tool;

                try
                {
                    FormsTool.UpdateRecords(new GrooveWebServicesV12Helpers.Forms2.RecordDataSet(DataSet));
                }
                catch (System.Exception Exception)
                {
                    base.StandardError.WriteLine("Unable to update dataset2: " + Exception.Message);
                    throw Exception;
                }
            }

			base.StandardOutput.WriteLine("<GrooveReplaceFormsRecordField RecordsReplaced='" + DataRows.Length + "'/>");
			
			return CommandUtils.UtilBase.CheckResult.Succeeded;
		}
	}
}